package com.sc.security.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sc.security.beans.LogService;
import com.sc.security.common.RequestHolder;
import com.sc.security.dao.SysRoleAclMapper;
import com.sc.security.model.SysRoleAcl;
import com.sc.security.service.RoleAclService;
import com.sc.security.utils.IpUtil;
import com.sc.security.utils.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.validator.internal.constraintvalidators.bv.past.PastValidatorForReadableInstant;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.Set;

@Service
public class RoleAclServiceImpl implements RoleAclService {
   @Autowired
   private SysRoleAclMapper roleAclMapper;
    @Autowired
    private LogService logService;

    @Override
    public void changeAcl(Integer lastRoleId, String aclIds) {
        List<Integer> idList = StringUtil.splitToListInt(aclIds);
        List<Integer> originIds = roleAclMapper.getAclIdListByRoleIdList(Lists.newArrayList(lastRoleId));
        if(originIds.size()==idList.size()){
            Set<Integer> oriSet = Sets.newHashSet(originIds);
            Set<Integer> idSet = Sets.newHashSet(idList);
            oriSet.removeAll(idSet);
            if(CollectionUtils.isEmpty(oriSet)){
                return;
            }
        }
        updateRoleAcls(lastRoleId,idList);
        logService.saveRoleAcl(lastRoleId,originIds,idList);
    }

    @Transactional
    public void updateRoleAcls(int roleId,List<Integer> idList){
        roleAclMapper.deleteByRoleID(roleId);
        if(CollectionUtils.isEmpty(idList)){
            return;
        }
        List<SysRoleAcl> roleAclList = Lists.newArrayList();
        for(Integer aclId:idList){
            SysRoleAcl roleAcl = SysRoleAcl.builder().roleId(roleId).aclId(aclId).
                    operateIp(IpUtil.getUserIP(RequestHolder.getCurrentRequest())).
                    operateTime(new Date()).operator(RequestHolder.getCurrentUser().getUsername()).build();
            roleAclList.add(roleAcl);
        }
        roleAclMapper.batchInsert(roleAclList);
    }
}
